package org.geektimes.projects.user.web.controller;

import org.apache.commons.collections.CollectionUtils;
import org.geektimes.projects.user.domain.User;
import org.geektimes.projects.user.service.UserService;
import org.geektimes.projects.user.service.impl.UserServiceImpl;
import org.geektimes.web.mvc.controller.PageController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * @Author 雪蓑
 * @Date: 2021/3/2 上午11:51
 * @Discription //todo
 */
@Path("/user")
public class UserController implements PageController{

    @Resource(name = "bean/UserService")
    private UserService userService;

    @Resource(name = "bean/Validator")
    private Validator validator;


    @Path("/register")
    @POST
    public String register(HttpServletRequest request, HttpServletResponse response){

        String username = request.getParameter("userName");
        User old = userService.queryUserByName(username);
        if(old != null ){
            return "fail.jsp";
        }

        String email = request.getParameter("email");
        String phoneNumber = request.getParameter("phoneNumber");
        //对手机号进行校验暂时想到了正则 + Pattern
        String checkPhone = "^1[3-9]\\\\d{9}$";
        Pattern.matches(checkPhone,phoneNumber);
        String password = request.getParameter("password");
        User user = new User();
        user.setEmail(email);
        user.setName(username);
        user.setPhoneNumber(phoneNumber);
        user.setPassword(password);

        checkParam(user);
        userService.register(user);
        return "success.jsp";
    }

    @Override
    @Path("/hello")
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Throwable {
        return "login-form.jsp";
    }

    /**
     * 校验入参
     * @param user
     */
    private void checkParam(User user){
        Set<ConstraintViolation<User>> violations = validator.validate(user);
        if(CollectionUtils.isNotEmpty(violations)){
            violations.forEach(c -> {
                //在项目中：1、可以直接抛自定义Exception，然后自定义一个@ControllerAdvice 去统一处理
                throw new RuntimeException(c.getMessage());
                //2、或者直接return到fail.jsp中 并且把c.getMessage()的信息传给jsp进行提示
            });
        }
    }
}
